package com.hainatong.shiphelper.module.cert.viewmodel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.blankj.utilcode.util.StringUtils;
import com.hainatong.shiphelper.Constants;
import com.hainatong.shiphelper.api.ApiResult;
import com.hainatong.shiphelper.api.ApiService;
import com.hainatong.shiphelper.api.HttpResult;
import com.hainatong.shiphelper.api.VMObserver;
import com.hainatong.shiphelper.mainhome.entity.WhereComBean;
import com.hainatong.shiphelper.module.cert.entity.CertChangeParam;
import com.hainatong.shiphelper.module.cert.entity.FileInfo;
import com.hainatong.shiphelper.module.cert.entity.ShipCertBean;
import com.hainatong.shiphelper.utils.GsonUtil;
import com.hainatong.mvvmbase.base.BaseViewModel;
import com.hainatong.mvvmbase.base.LiveResult;
import com.hainatong.mvvmbase.base.PageLiveResult;
import com.hainatong.mvvmbase.http.RxSchedulersUtils;

import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;
import io.reactivex.disposables.Disposable;

public class CertViewModel extends BaseViewModel
{

    public CertViewModel(@NonNull Application application)
    {
        super(application);
    }


    private MutableLiveData<LiveResult<FileInfo>> fileInfoResult = new MutableLiveData<>();

    public MutableLiveData<LiveResult<FileInfo>> getFileInfoResult()
    {
        return fileInfoResult;
    }

    /**
     *  查询 证书 网络链接
     * @param
     */
    public void queryFileInfoById(String uuid)
    {

        ApiService.Builder.getChanBoServer()
                          .getFileInfoById( uuid )
                          .compose( RxSchedulersUtils.Obs_io_main() )
                          .subscribe(new VMObserver<ApiResult<FileInfo>>()
                          {
                              @Override
                              public void onStart(Disposable d)
                              {
                                  addDisposable( d );
                              }

                              @Override
                              public void onError(int code, String errorMsg)
                              {
                                  getFileInfoResult().postValue( new LiveResult<>( false ,errorMsg ) );
                              }

                              @Override
                              public void onSuccess(ApiResult<FileInfo> result)
                              {

                                  if( result.isOk() )
                                  {
                                      getFileInfoResult().postValue( new LiveResult<>( true , result.getData()) );
                                  }
                                  else
                                  {
                                      getFileInfoResult().postValue( new LiveResult<>( false , result.getMessage() ) );
                                  }
                              }
                          });

    }


    private MutableLiveData<LiveResult<ShipCertBean>> shipCertDetailResult = new MutableLiveData<>();

    public MutableLiveData<LiveResult<ShipCertBean>> getShipCertDetailResult()
    {
        return shipCertDetailResult;
    }

    /**
     *  查询 船舶 cert 详情
     * @param
     */
    public void queryShipCertDetailById(String uuid)
    {

        ApiService.Builder.getChanBoServer()
                          .getShipCertById( uuid )
                          .compose( RxSchedulersUtils.Obs_io_main() )
                .subscribe(new VMObserver<ApiResult<ShipCertBean>>()
                {
                    @Override
                    public void onStart(Disposable d)
                    {
                        addDisposable( d );
                    }

                    @Override
                    public void onError(int code, String errorMsg)
                    {
                        getShipCertDetailResult().postValue( new LiveResult<>( false ,errorMsg ) );
                    }

                    @Override
                    public void onSuccess(ApiResult<ShipCertBean> result)
                    {

                        if( result.isOk() )
                        {
                            getShipCertDetailResult().postValue( new LiveResult<>( true , result.getData()) );
                        }
                        else
                        {
                            getShipCertDetailResult().postValue( new LiveResult<>( false , result.getMessage() ) );
                        }
                    }
                });

    }



    private int page;

    private boolean isRefresh = false;

    private boolean isHasNextPage = false;

    private String keyWord;


    private MutableLiveData<PageLiveResult<List<ShipCertBean>>> shipCertListResult = new MutableLiveData<>();

    public MutableLiveData<PageLiveResult<List<ShipCertBean>>> getShipCertListResult()
    {
        return shipCertListResult;
    }

    /**
     *  查询 船舶证书 列表
     */
    private void queryShipCertList(int mPage,String keyName)
    {
        //{"wheres":"[{}]","rows":"50","page":"1"}
        Map<String,Object> param = new HashMap<String,Object>();
        param.put(Constants.Key.PAGE, String.valueOf( mPage ) );
        param.put(Constants.Key.ROWS, String.valueOf( Constants.DEF_PAGE_SIZE  ));
        // 查询 参数
        List<WhereComBean> whereList = new ArrayList<>();
        whereList.add( new WhereComBean( "cert_name", keyName ) );
        if(!StringUtils.isEmpty( keyName ))
        {
            param.put( "wheres", GsonUtil.obj2json( whereList ));
        }

        ApiService.Builder.getChanBoServer()
                          .getShipCertList(param)
                          .compose( RxSchedulersUtils.Obs_io_main() )
                          .subscribe(new VMObserver<HttpResult<List<ShipCertBean>>>()
                          {
                    @Override
                    public void onStart(Disposable d)
                    {
                        addDisposable( d );
                    }

                    @Override
                    public void onError(int code, String errorMsg)
                    {
                        PageLiveResult<List<ShipCertBean>> errorResult = new PageLiveResult<>();
                        errorResult.setSuccess(false);
                        errorResult.setRefresh(isRefresh);
                        errorResult.setMsg(errorMsg);
                        if( !isRefresh )
                        {
                            errorResult.setLoadMoreEmpty(true);
                        }
                        getShipCertListResult().postValue( errorResult );
                    }

                    @Override
                    public void onSuccess(HttpResult<List<ShipCertBean>> result)
                    {
                        if( result.isOk() )
                        {
                            PageLiveResult<List<ShipCertBean>> listResult = new PageLiveResult<>();
                            listResult.setSuccess(true);
                            listResult.setRefresh(isRefresh);
                            if( result.getRows() != null && !result.getRows().isEmpty() )
                            {
                                listResult.setData( result.getRows() );
                                if( result.getRows().size() < Constants.DEF_PAGE_SIZE )
                                {
                                    isHasNextPage = false;
                                }
                                else
                                {
                                    isHasNextPage = true;
                                    page = page + 1;
                                }
                            }
                            getShipCertListResult().postValue(listResult);
                        }
                        else
                        {
                            PageLiveResult<List<ShipCertBean>> failResult = new PageLiveResult<>();
                            failResult.setSuccess(false);
                            failResult.setRefresh(isRefresh);
                            failResult.setMsg(result.getMsg());
                            if( !isRefresh )
                            {
                                failResult.setLoadMoreEmpty(true);
                            }
                            getShipCertListResult().postValue(failResult);
                        }
                    }
                });

    }


    public void queryShipCert(String keyName)
    {
        this.page = 1;
        this.isRefresh = true;
        this.isHasNextPage = true;
        this.keyWord = keyName;
        queryShipCertList( this.page,keyName );
    }

    public void tryRefresh()
    {
        queryShipCert(this.keyWord);
    }

    public void loadMore()
    {
        if( isHasNextPage )
        {
            this.isRefresh = false;
            queryShipCertList(this.page,this.keyWord);
        }
        else
        {
            PageLiveResult<List<ShipCertBean>> emptyResult = new PageLiveResult<>();
            emptyResult.setSuccess(false);
            emptyResult.setLoadMoreEmpty(true);
            emptyResult.setRefresh(false);
            getShipCertListResult().postValue(emptyResult);
        }
    }



    private MutableLiveData<LiveResult<Object>> certChangeResult = new MutableLiveData<>();

    public MutableLiveData<LiveResult<Object>> getCertChangeResult()
    {
        return certChangeResult;
    }

    public void submitChangeCertTask(CertChangeParam param)
    {

        ApiService.Builder.getChanBoServer()
                          .submitShipCertChangeTask( param )
                          .compose( RxSchedulersUtils.Obs_io_main() )
                          .subscribe(new VMObserver<ApiResult<Object>>()
                          {
                              @Override
                              public void onStart(Disposable d)
                              {
                                 addDisposable( d );
                              }

                              @Override
                              public void onError(int code, String errorMsg)
                              {
                                  getCertChangeResult().postValue( new LiveResult<>( false ,errorMsg ) );
                              }

                              @Override
                              public void onSuccess(ApiResult<Object> result)
                              {
                                  if( result.getCode().equals("311") )
                                  {
                                      getCertChangeResult().postValue( new LiveResult<>( true ,result.getData() ) );
                                  }
                                  else
                                  {
                                      getCertChangeResult().postValue( new LiveResult<>( false ,result.getMessage() ) );
                                  }
                              }
                          });

    }



}
